<template>
  <el-dialog :title="dialogTitle" width="60%" @close="handleClose">
    <el-form :model="form" label-width="70px" ref="formRef" :rules="{}">
      <el-transfer
        v-model="form.jobIdList"
        filterable
        filter-placeholder="State Abbreviations"
        :data="allJobList"
        :titles="['岗位', '已选中的岗位']"
      />
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { updateUserJob } from '@/api/user.js'
import { ElMessage } from 'element-plus'
import i18n from '@/i18n'
const emits = defineEmits(['update:modelValue', 'initUserList'])
const formRef = ref(null)
const form = ref({
  jobIdList: []
})

const props = defineProps({
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogTableVal: {
    type: Object,
    // default: {} 此处会报错 因为vue规定，对象或数组默认值必须从一个工厂函数获取
    default: function () {
      return {}
    }
  },
  jobIdList: {
    type: Array,
    default: function () {
      return []
    }
  },
  allJobList: {
    type: Array,
    default: function () {
      return []
    }
  }
})

watch(
  () => props.dialogTableVal,
  () => {
    form.value = props.dialogTableVal
  },
  { deep: true, immediate: true }
)

const handleClose = () => {
  emits('update:modelValue', false)
}

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      await updateUserJob({
        id: form.value.id,
        jobIdList: form.value.jobIdList
      })
      ElMessage({
        message: i18n.global.t('userMessage.updateSuccess'),
        type: 'success'
      })
      emits('initUserList')
      handleClose()
    } else {
      console.log('error submit!!')
      return false
    }
  })
}
</script>

<style lang="scss" scoped></style>
